<template>
  <div class="cms-categories-container">
    <el-card shadow="never">
      <template #header>
        <div class="card-header">
          <span>栏目管理</span>
          <el-button type="primary" @click="handleAdd">
            <el-icon><Plus /></el-icon>
            新增栏目
          </el-button>
        </div>
      </template>

      <!-- 搜索区域 -->
      <div class="search-box">
        <el-input
          v-model="searchText"
          placeholder="搜索栏目名称"
          clearable
          style="width: 300px; margin-bottom: 20px"
          @input="handleSearch"
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
      </div>

      <!-- 树形表格 -->
      <el-table
        :data="tableData"
        border
        stripe
        row-key="id"
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
        v-loading="loading"
        default-expand-all
        style="width: 100%"
      >
        <el-table-column prop="name" label="栏目名称" min-width="200">
          <template #default="{ row }">
            <el-icon v-if="row.icon" style="margin-right: 5px">
              <component :is="row.icon" />
            </el-icon>
            <span>{{ row.name }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="slug" label="栏目标识" width="150" />
        <el-table-column prop="articleCount" label="文章数" width="100" align="center">
          <template #default="{ row }">
            <el-tag type="primary">{{ row.articleCount }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="sort" label="排序" width="100" align="center" />
        <el-table-column prop="status" label="状态" width="100" align="center">
          <template #default="{ row }">
            <el-switch
              v-model="row.status"
              :active-value="1"
              :inactive-value="0"
              @change="handleStatusChange(row)"
            />
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180" />
        <el-table-column label="操作" width="280" align="center" fixed="right">
          <template #default="{ row }">
            <el-button 
              type="primary" 
              size="small" 
              link
              @click="handleAddChild(row)"
            >
              <el-icon><Plus /></el-icon>
              新增子栏目
            </el-button>
            <el-button 
              type="primary" 
              size="small" 
              link
              @click="handleEdit(row)"
            >
              <el-icon><Edit /></el-icon>
              编辑
            </el-button>
            <el-button 
              type="danger" 
              size="small" 
              link
              @click="handleDelete(row)"
            >
              <el-icon><Delete /></el-icon>
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 新增/编辑栏目弹窗 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="600px"
      :close-on-click-modal="false"
      @close="handleDialogClose"
    >
      <el-form 
        ref="formRef" 
        :model="form" 
        :rules="rules" 
        label-width="100px"
      >
        <el-form-item label="栏目名称" prop="name">
          <el-input 
            v-model="form.name" 
            placeholder="请输入栏目名称"
            maxlength="50"
          />
        </el-form-item>

        <el-form-item label="栏目标识" prop="slug">
          <el-input 
            v-model="form.slug" 
            placeholder="请输入栏目标识（英文）"
          />
          <el-text size="small" type="info">用于URL访问，如：news、products</el-text>
        </el-form-item>

        <el-form-item label="上级栏目">
          <el-tree-select
            v-model="form.parentId"
            :data="categoryTreeData"
            :props="{ value: 'id', label: 'name', children: 'children' }"
            placeholder="请选择上级栏目（不选则为顶级栏目）"
            clearable
            check-strictly
            style="width: 100%"
          />
        </el-form-item>

        <el-form-item label="栏目图标">
          <el-select 
            v-model="form.icon" 
            placeholder="请选择图标"
            clearable
            style="width: 100%"
          >
            <el-option label="文件夹" value="Folder" />
            <el-option label="文档" value="Document" />
            <el-option label="新闻" value="Tickets" />
            <el-option label="产品" value="Box" />
            <el-option label="技术" value="Monitor" />
            <el-option label="分享" value="Share" />
          </el-select>
        </el-form-item>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="排序" prop="sort">
              <el-input-number 
                v-model="form.sort" 
                :min="0" 
                controls-position="right"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态">
              <el-switch 
                v-model="form.status" 
                :active-value="1" 
                :inactive-value="0"
                active-text="启用"
                inactive-text="禁用"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="栏目描述">
          <el-input 
            v-model="form.description" 
            type="textarea"
            :rows="3"
            placeholder="请输入栏目描述"
            maxlength="200"
            show-word-limit
          />
        </el-form-item>

        <el-divider>SEO设置</el-divider>

        <el-form-item label="SEO标题">
          <el-input 
            v-model="form.seoTitle" 
            placeholder="留空则使用栏目名称"
            maxlength="60"
          />
        </el-form-item>

        <el-form-item label="SEO关键词">
          <el-input 
            v-model="form.seoKeywords" 
            placeholder="多个关键词用逗号分隔"
          />
        </el-form-item>

        <el-form-item label="SEO描述">
          <el-input 
            v-model="form.seoDescription" 
            type="textarea"
            :rows="2"
            placeholder="留空则使用栏目描述"
            maxlength="160"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit" :loading="submitLoading">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Search, Edit, Delete, Folder } from '@element-plus/icons-vue'

// 搜索文本
const searchText = ref('')

// 表格数据
const tableData = ref([])
const loading = ref(false)

// 对话框
const dialogVisible = ref(false)
const dialogTitle = ref('新增栏目')
const formRef = ref()
const submitLoading = ref(false)

// 表单数据
const form = reactive({
  id: null,
  name: '',
  slug: '',
  parentId: null,
  icon: '',
  sort: 0,
  status: 1,
  description: '',
  seoTitle: '',
  seoKeywords: '',
  seoDescription: ''
})

// 栏目树数据（用于选择上级栏目）
const categoryTreeData = computed(() => {
  // 如果是编辑模式，需要排除当前节点及其子节点
  if (form.id) {
    return filterCurrentNode(tableData.value, form.id)
  }
  return tableData.value
})

// 过滤当前节点
const filterCurrentNode = (data, currentId) => {
  return data.filter(item => {
    if (item.id === currentId) {
      return false
    }
    if (item.children && item.children.length > 0) {
      item.children = filterCurrentNode(item.children, currentId)
    }
    return true
  })
}

// 表单验证规则
const rules = {
  name: [
    { required: true, message: '请输入栏目名称', trigger: 'blur' }
  ],
  slug: [
    { required: true, message: '请输入栏目标识', trigger: 'blur' },
    { pattern: /^[a-z0-9-]+$/, message: '只能包含小写字母、数字和连字符', trigger: 'blur' }
  ],
  sort: [
    { required: true, message: '请输入排序', trigger: 'blur' }
  ]
}

// 搜索
const handleSearch = () => {
  if (!searchText.value) {
    loadData()
    return
  }
  // 实际应该调用后端搜索接口
  ElMessage.info('搜索：' + searchText.value)
}

// 新增
const handleAdd = () => {
  dialogTitle.value = '新增栏目'
  form.parentId = null
  dialogVisible.value = true
}

// 新增子栏目
const handleAddChild = (row) => {
  dialogTitle.value = '新增子栏目'
  form.parentId = row.id
  dialogVisible.value = true
}

// 编辑
const handleEdit = (row) => {
  dialogTitle.value = '编辑栏目'
  Object.assign(form, { ...row })
  dialogVisible.value = true
}

// 删除
const handleDelete = (row) => {
  if (row.articleCount > 0) {
    ElMessage.warning('该栏目下还有文章，无法删除')
    return
  }
  if (row.children && row.children.length > 0) {
    ElMessage.warning('该栏目下还有子栏目，无法删除')
    return
  }

  ElMessageBox.confirm(
    `确定要删除栏目"${row.name}"吗？`,
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    ElMessage.success('删除成功')
    loadData()
  }).catch(() => {})
}

// 状态变更
const handleStatusChange = (row) => {
  const statusText = row.status === 1 ? '启用' : '禁用'
  ElMessage.success(`已${statusText}栏目：${row.name}`)
}

// 提交
const handleSubmit = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate(async (valid) => {
    if (valid) {
      submitLoading.value = true
      try {
        // 模拟API调用
        await new Promise(resolve => setTimeout(resolve, 1000))
        
        const action = form.id ? '更新' : '新增'
        ElMessage.success(`${action}成功`)
        
        dialogVisible.value = false
        loadData()
      } catch (error) {
        ElMessage.error('操作失败：' + error.message)
      } finally {
        submitLoading.value = false
      }
    }
  })
}

// 对话框关闭
const handleDialogClose = () => {
  formRef.value?.resetFields()
  form.id = null
  form.parentId = null
}

// 加载数据
const loadData = async () => {
  loading.value = true
  try {
    // 模拟数据
    await new Promise(resolve => setTimeout(resolve, 500))
    
    tableData.value = [
      {
        id: 1,
        name: '公司新闻',
        slug: 'news',
        icon: 'Tickets',
        articleCount: 15,
        sort: 1,
        status: 1,
        createTime: '2024-01-01 10:00:00',
        children: [
          {
            id: 11,
            name: '公司动态',
            slug: 'company-news',
            icon: '',
            articleCount: 8,
            sort: 1,
            status: 1,
            createTime: '2024-01-02 10:00:00'
          },
          {
            id: 12,
            name: '媒体报道',
            slug: 'media-news',
            icon: '',
            articleCount: 7,
            sort: 2,
            status: 1,
            createTime: '2024-01-02 11:00:00'
          }
        ]
      },
      {
        id: 2,
        name: '行业动态',
        slug: 'industry',
        icon: 'Monitor',
        articleCount: 23,
        sort: 2,
        status: 1,
        createTime: '2024-01-01 11:00:00'
      },
      {
        id: 3,
        name: '产品资讯',
        slug: 'products',
        icon: 'Box',
        articleCount: 31,
        sort: 3,
        status: 1,
        createTime: '2024-01-01 12:00:00',
        children: [
          {
            id: 31,
            name: '新品发布',
            slug: 'new-products',
            icon: '',
            articleCount: 12,
            sort: 1,
            status: 1,
            createTime: '2024-01-03 10:00:00'
          },
          {
            id: 32,
            name: '产品更新',
            slug: 'product-updates',
            icon: '',
            articleCount: 19,
            sort: 2,
            status: 1,
            createTime: '2024-01-03 11:00:00'
          }
        ]
      },
      {
        id: 4,
        name: '技术文章',
        slug: 'tech',
        icon: 'Document',
        articleCount: 45,
        sort: 4,
        status: 1,
        createTime: '2024-01-01 13:00:00'
      },
      {
        id: 5,
        name: '经验分享',
        slug: 'sharing',
        icon: 'Share',
        articleCount: 18,
        sort: 5,
        status: 1,
        createTime: '2024-01-01 14:00:00'
      }
    ]
  } catch (error) {
    ElMessage.error('加载数据失败：' + error.message)
  } finally {
    loading.value = false
  }
}

onMounted(() => {
  loadData()
})
</script>

<style scoped>
.cms-categories-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-box {
  margin-bottom: 20px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style>

